<template>
  <div class="broad">
    <div class="left_adv"> TODO </div>
    <div ref="centerPlayer" class="center_player">
      <!-- <NPlayer ref="nplayer" :set="setPlayer" /> -->
    </div>
    <div class="right_chat"> TODO </div>
  </div>
  <div class="bottom"> </div>
</template>
<script lang="ts">
  import { ref } from 'vue';
  import NPlayer, { Popover } from 'nplayer';
  import Danmaku from '@nplayer/danmaku';
  import Hls from 'hls.js';
  import './style.less';
  export default {
    components: {},
    setup() {
      let player = null;
      const centerPlayer = ref(null);

      // 右键菜单增加截图
      const Screenshot = {
        html: '截图',
        click(player) {
          const canvas = document.createElement('canvas');
          canvas.width = player.video.videoWidth;
          canvas.height = player.video.videoHeight;
          canvas.getContext('2d').drawImage(player.video, 0, 0, canvas.width, canvas.height);
          canvas.toBlob((blob) => {
            let dataURL = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = dataURL;
            link.download = 'NPlayer.png';
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(dataURL);
          });
        },
      };

      // 插件设置
      // 速度设置
      const speedSettingItem = (): SettingItem => ({
        id: 'speed',
        html: '播放速度',
        type: 'select',
        value: 1,
        options: [
          { value: 2, html: '2' },
          { value: 1.5, html: '1.5' },
          { value: 1, html: '正常' },
          { value: 0.5, html: '0.5' },
          { value: 0.25, html: '0.25' },
        ],
        init(player) {
          player.playbackRate = 1;
        },
        change(value, player) {
          this.value = player.playbackRate = value;
        },
      });
      // 1. 首先创建一个清晰度控制条项
      const Quantity = {
        el: document.createElement('div'),
        init() {
          this.btn = document.createElement('div');
          this.btn.textContent = '画质';

          this.el.appendChild(this.btn);
          this.popover = new Popover(this.el);
          this.btn.addEventListener('click', () => this.popover.show());
          // 点击按钮的时候展示 popover
          // 默认隐藏
          this.el.style.display = 'none';
          this.el.classList.add('quantity');
          this.btn.classList.add('quantity_btn');
        },
      };
      const newPlugin = {
        apply(player) {
          player.registerSettingItem(speedSettingItem(), 'speed');
        },
      };

      // 弹幕设置
      const danmakuOptions = {
        items: [{ time: 1, text: '前方弹幕来袭～' }],
      };

      //初始化播放器
      const initPlayer = () => {
        // 设置视频
        const video = document.createElement('video');
        // video.src = '/resource/video/280443.mp4';
        player = new NPlayer({
          seekStep: 10,
          volumeStep: 0.1,
          video: video,
          videoProps: { autoplay: 'true' },
          contextMenus: [Screenshot, 'loop', 'pip'],
          contextMenuToggle: true,
          controls: [
            [
              'play',
              'volume',
              'time',
              'spacer',
              Quantity,
              'airplay',
              'settings',
              'web-fullscreen',
              'fullscreen',
            ],
            ['progress'],
          ],
          bpControls: {},
          plugins: [new Danmaku(danmakuOptions), newPlugin],
        });

        // 绑定流
        const hls = new Hls();
        hls.on(Hls.Events.MEDIA_ATTACHED, function () {
          hls.on(Hls.Events.MANIFEST_PARSED, function () {
            // 4. 给清晰度排序，清晰度越高的排在最前面
            hls.levels.sort((a, b) => b.height - a.height);
            const frag = document.createDocumentFragment();
            // 5. 给与清晰度对应的元素添加，点击切换清晰度功能
            const listener = (i) => (init) => {
              const last = Quantity.itemElements[Quantity.itemElements.length - 1];
              const prev = Quantity.itemElements[Quantity.value] || last;
              const el = Quantity.itemElements[i] || last;
              prev.classList.remove('quantity_item-active');
              el.classList.add('quantity_item-active');
              Quantity.btn.textContent = el.textContent;
              if (init !== true && !player.paused) setTimeout(() => player.play());
              // 因为 HLS 切换清晰度会使正在播放的视频暂停，我们这里让它再自动恢复播放
              Quantity.value = hls.currentLevel = hls.loadLevel = i;
              Quantity.popover.hide();
            };
            // 6. 添加清晰度对应元素
            Quantity.itemElements = hls.levels.map((l, i) => {
              const el = document.createElement('div');
              el.textContent = l.name + 'P';
              if (l.height === 1080) el.textContent += ' 超清';
              if (l.height === 720) el.textContent += ' 高清';
              if (l.height === 480) el.textContent += ' 清晰';
              el.classList.add('quantity_item');
              el.addEventListener('click', listener(i));
              frag.appendChild(el);
              return el;
            });

            const el = document.createElement('div');
            el.classList.add('quantity_item');
            el.textContent = '自动';
            el.addEventListener('click', listener(-1));
            frag.appendChild(el);
            Quantity.itemElements.push(el);
            // 这里再添加一个 `自动` 选项，HLS 默认是根据网速自动切换清晰度
            Quantity.popover.panelEl.appendChild(frag);
            Quantity.el.style.display = 'block';
            listener(hls.currentLevel)(true);
            // 初始化当前清晰度
          });

          // 绑定 video 元素成功的时候，去加载视频
          // hls.loadSource('https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8');
          hls.loadSource('http://127.0.0.1:81/hls/test1/index.m3u8');
        });
        hls.attachMedia(video);
        player.mount(centerPlayer.value);
      };
      return {
        player,
        initPlayer,
        centerPlayer,
        setPlayer: (p) => (player = p),
      };
    },
    mounted() {
      this.initPlayer();
      console.log(this.player);
    },
  };
</script>
<style lang="less" scoped>
  .tab-header {
    background: white;
    padding-left: 1%;
    padding-right: 1%;
  }
  .broad {
    display: flex;
    width: 100%;
    height: 80%;
  }
  .left_adv {
    width: 60px;
    border: #222222 2px solid;
  }
  .center_player {
    flex: 1;
    border: #222222 2px solid;
    border-left: 0px;
    border-right: 0px;
  }
  .right_chat {
    width: 400px;
    border: #222222 2px solid;
  }
  .bottom {
    width: 100%;
    height: 20%;
    border: #222222 2px solid;
    border-top: 0px;
  }
</style>
